<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入试卷名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="分类" prop="type">
        <div class="treeselect" style="width: 300px">
          <treeselect v-model="queryParams.type" :options="typeOptions"
                      :show-count="true" :normalizer="normalizer" @select="handleNodeClickquery" placeholder="选择类型"
          />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:ks:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:ks:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:ks:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="试卷名称" align="center" prop="name"/>
      <!--      <el-table-column label="图标" align="center" prop="image" width="100">-->
      <!--        <template slot-scope="scope">-->
      <!--          <image-preview :src="scope.row.image" :width="50" :height="50"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="考试分类" align="center" prop="ksTypeName"/>
      <el-table-column label="部门" align="center" prop="deptName"/>
      <el-table-column label="岗位" align="center" prop="postName"/>
      <!--      <el-table-column label="岗位Id" align="center" prop="postId" />-->
      <el-table-column label="工龄范围(月)" align="center" prop="glMin" width="100">
        <template slot-scope="scope">
          {{ scope.row.glMin }} - {{ scope.row.glMax }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160"></el-table-column>

<!--      <el-table-column label="状态" align="center" prop="status"/>-->
      <!--      <el-table-column label="时间(分钟)" align="center" prop="times" />-->
      <!--      <el-table-column label="排序号" align="center" prop="orderNum" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:ks:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:ks:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" :width="dialogWidth" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入试卷名称"/>
        </el-form-item>
        <el-form-item label="课程分类" prop="type">
          <div class="treeselect">
            <treeselect v-model="form.type" :options="typeOptions"
                        :show-count="true" :normalizer="normalizer" @select="handleNodeClick" placeholder="选择类型"
            />
          </div>
        </el-form-item>

        <el-form-item label="部门" prop="deptList">
          <el-select v-model="form.deptList" placeholder="请选择部门" clearable multiple>
            <el-option
              v-for="item in deptOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="岗位" prop="postList">
          <el-select v-model="form.postList" placeholder="请选择岗位" clearable multiple>
            <el-option
              v-for="item in postOptions"
              :key="item.postId"
              :label="item.postName"
              :value="item.postId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="工龄最小值(月)" prop="glMin">
          <el-input-number v-model="form.glMin" placeholder="请输入工龄最小值" :min="0" :max="1000"/>
        </el-form-item>
        <el-form-item label="工龄最大值(月)" prop="glMax">
          <el-input-number v-model="form.glMax" placeholder="请输入工龄最大值" :min="1" :max="1000"/>
        </el-form-item>
        <el-form-item label="试卷介绍" prop="remark">
          <el-input v-model="form.remark" type="textarea"/>
        </el-form-item>
        <el-form-item label="考试时间(分钟)" prop="times">
          <el-input-number v-model="form.times" placeholder="请输入考试时间" :min="1"/>
        </el-form-item>
        <el-form-item label="选择试题">
          <div style="display: flex">
            <div><span>选择题数量/分数</span><span class="labeltitle" style="margin-left: 20px"
            >{{ selectNum }}/{{ selectNumScore }}</span></div>
            <div style="margin-left: 20px"><span>判断题数量/分数</span><span class="labeltitle"
                                                                             style="margin-left: 20px"
            >{{ panduanNum }}/{{ panduanScore }}</span></div>
            <div style="margin-left: 20px"><span>总数量</span><span class="labeltitle">{{ totalNum }}</span></div>
            <div style="margin-left: 20px"><span>总分数</span><span class="labeltitle">{{ selectScore }}</span></div>
          </div>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="selectSt">添加试题</el-button>
          <div style="height: 300px;overflow: auto">
            <el-table :data="form.quList" @cell-dblclick="handleCellDblclick">
              <el-table-column label="主键" align="center" prop="id"/>
              <el-table-column label="试题Id" align="center" prop="quId"/>
              <el-table-column label="题目名称" align="center" prop="title"/>
              <el-table-column label="试题类型" align="center" prop="quType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.qu_type" :value="scope.row.quType"/>
                </template>
              </el-table-column>
              <el-table-column label="分值" align="center" prop="score" width="200">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.score" :min="0" @blur="handleScoreBlur(scope.row)"
                                   @keyup.enter.native="handleScoreBlur(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="分类" align="center" prop="typeName"/>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDeleteSt(scope.row)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="selectQuOpen" :width="dialogWidth" append-to-body>
      <question @selectQuestion="selectQuestion" viewType="selectqu"></question>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelQudialog ">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listKs, getKs, delKs, addKs, updateKs } from '@/api/business/ks'
import { delQuestion } from '@/api/business/ksqu'
import question from '@/components/question'
import { allPost } from '@/api/system/post'
import { getDeptlist } from '@/api/system/dept'
import { listType } from '@/api/business/kstype'

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Ks',
  dicts: ['qu_type'],
  components: { question, Treeselect },
  data() {
    return {
      tableData: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      selectQuOpen: false,
      // 总条数
      total: 0,
      // 试卷表格数据
      ksList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        image: null,
        type: null,
        deptId: null,
        postId: null,
        glMin: null,
        glMax: null,
        status: null,
        times: null,
        orderNum: null

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '试卷名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '分类不能为空', trigger: 'blur' }
        ],
        postList: [
          { required: true, message: '岗位不能为空', trigger: 'blur' }
        ],
        deptList: [
          { required: true, message: '部门不能为空', trigger: 'blur' }
        ],
        times : [
          { required: true, message: '考试时长不能为空', trigger: 'blur' }
        ],
        glMin : [
          { required: true, message: '工龄最小值不能为空', trigger: 'blur' }
        ],
        glMax : [
          { required: true, message: '工龄最大值不能为空', trigger: 'blur' }
        ],
      },
      postOptions: [],
      deptOptions: [],
      typeOptions: []
    }
  },
  created() {
    this.getList()
    listType().then(response => {
      this.typeOptions = this.handleTree(response.data, 'id')
    })
    this.getPostAll()
    this.getDeptAll()
  },
  computed: {

    dialogWidth() {
      const maxWidth = 1200 // 最大宽度
      const screenWidth = window.innerWidth // 屏幕宽度
      return `${Math.min(maxWidth, screenWidth - 60)}px` // 减去60是为了留出一些边距
    },
    selectNum() {
      var num = 0
      if (this.form.quList) {
        this.form.quList.forEach(item => {
          if (item.quType == 1) {
            num++
          }
        })
        return num
      }
    },
    selectNumScore() {
      var num = 0
      if (this.form.quList) {
        this.form.quList.forEach(item => {
          if (item.quType == 1) {
            num += item.score
          }
        })
        return num
      }
    },
    totalNum() {
      if (this.form.quList) {
        return this.form.quList.length
      }
    },
    panduanNum() {
      var num = 0
      if (this.form.quList) {
        this.form.quList.forEach(item => {
          if (item.quType == 2) {
            num++
          }
        })
        return num
      }
    },
    panduanScore() {
      var num = 0
      if (this.form.quList) {
        this.form.quList.forEach(item => {
          if (item.quType == 2) {
            num += item.score
          }
        })
        return num
      }
    },
    selectScore() {
      // 计算总分数 score
      var num = 0
      if (this.form.quList) {
        this.form.quList.forEach(item => {
          num += item.score
        })
        return num
      }

    }
  },
  methods: {
    handleNodeClickquery(data) {

    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    handleNodeClick(data) {
      if (data.parentId == '0') {
        this.$modal.msgError('请选择二级节点')
      }
      return
    },
    // 获取所有的岗位
    getPostAll() {
      allPost({}).then(response => {
        this.postOptions = response.data
      })

    },
    getDeptAll() {
      getDeptlist({ }).then(response => {
        this.deptOptions = response.data
      })

    },
    handleCellDblclick(row, column, cell, event) {
      if (column.property === 'score') {
        row.editing = true
      }
    },
    handleScoreBlur(row) {
      row.editing = false
      // 只能是数字

      // 你可以在这里添加保存分值的逻辑
      console.log('分值已更新:', row)
    },
    selectQuestion(val) {
      // 遍历val
      val.forEach(item => {
        var json = {
          quId: item.id,
          title: item.title,
          quType: item.quType,
          score: 1,
          typeName: item.typeName
        }
        this.form.quList.push(json)
      })
      this.selectQuOpen = false

    },
    /** 查询试卷列表 */
    getList() {
      this.loading = true
      listKs(this.queryParams).then(response => {
        this.ksList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancelQudialog() {
      this.selectQuOpen = false
      this.reset()
    },

    selectSt() {
      this.title = '选择试题'
      this.selectQuOpen = true
    },
    handleDeleteSt(row) {
      this.form.quList.splice(row, 1)
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        image: null,
        type: null,
        deptId: null,
        postId: null,
        glMin: null,
        glMax: null,
        status: null,
        times: null,
        orderNum: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
        quList: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加试卷'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getKs(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改试卷'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.glMax == this.form.glMin  ||   this.form.glMax < this.form.glMin) {
              this.$modal.msgError('工龄最大值应该大于工龄最小值')
              return
            }
            updateKs(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addKs(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除试卷编号为"' + ids + '"的数据项？').then(function() {
        return delKs(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/ks/export', {
        ...this.queryParams
      }, `ks_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style>
.labeltitle {
  font-weight: bold;
  font-size: 16px;
}

</style>
